<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="员工ID" prop="employeeId">
        <el-input
          v-model="queryParams.employeeId"
          placeholder="请输入员工ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工资月份" prop="salaryMonth">
        <el-input
          v-model="queryParams.salaryMonth"
          placeholder="请输入工资月份"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['payment:payment:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['payment:payment:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['payment:payment:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['payment:payment:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="paymentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="工资发放I" align="center" prop="id" /> -->
      <el-table-column label="员工姓名" align="center" prop="name" />
      <el-table-column label="员工工号" align="center" prop="employeeNumber" />
      <el-table-column label="工资月份" align="center" prop="salaryMonth" />
      <el-table-column label="发放状态" align="center" prop="paymentStatus">
        <template #default="scope">
          <dict-tag :options="payment_status" :value="scope.row.paymentStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="实际发放日期" align="center" prop="paymentDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.paymentDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handlePayment(scope.row)" v-hasPermi="['payment:payment:edit']">发放</el-button>
          <el-button link type="primary" icon="Document" @click="handleSlip(scope.row)" v-hasPermi="['payment:payment:edit']">工资条</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['payment:payment:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工资发放记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="paymentRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="员工ID" prop="employeeId">
          <el-input v-model="form.employeeId" placeholder="请输入员工ID" />
        </el-form-item>
        <el-form-item label="工资月份" prop="salaryMonth">
          <el-input v-model="form.salaryMonth" placeholder="请输入工资月份" />
        </el-form-item>
        <el-form-item label="发放状态" prop="paymentStatus">
          <el-select v-model="form.paymentStatus" placeholder="请选择发放状态">
            <el-option
              v-for="dict in payment_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 工资条信息对话框 -->
    <el-dialog title="工资条信息" v-model="slipOpen" width="500px" append-to-body>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="加班时长">{{ slipInfo.overtimeHours }}</el-descriptions-item>
        <el-descriptions-item label="请假时长">{{ slipInfo.leaveHours }}</el-descriptions-item>
        <el-descriptions-item label="基本工资">{{ slipInfo.basicSalary }}</el-descriptions-item>
        <el-descriptions-item label="加班补贴">{{ slipInfo.overtimeAllowance }}</el-descriptions-item>
        <el-descriptions-item label="请假扣款">{{ slipInfo.leaveDeduction }}</el-descriptions-item>
        <el-descriptions-item label="个人所得税">{{ slipInfo.incomeTax }}</el-descriptions-item>
        <el-descriptions-item label="社保扣除">{{ slipInfo.socialInsurance }}</el-descriptions-item>
        <el-descriptions-item label="实发工资">{{ slipInfo.totalSalary }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="slipOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Payment">
import { listPayment, getPayment, delPayment, addPayment, updatePayment, getSlip } from "@/api/payment/payment"

const { proxy } = getCurrentInstance()
const { payment_status } = proxy.useDict('payment_status')

const paymentList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const slipOpen = ref(false)
const slipInfo = ref({})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    employeeId: null,
    salaryMonth: null,
  },
  rules: {
    employeeId: [
      { required: true, message: "员工ID，关联员工表不能为空", trigger: "blur" }
    ],
    salaryMonth: [
      { required: true, message: "工资月份，格式YYYY-MM不能为空", trigger: "blur" }
    ],
    paymentStatus: [
      { required: true, message: "发放状态：待发放/已发放不能为空", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询工资发放记录列表 */
function getList() {
  loading.value = true
  listPayment(queryParams.value).then(response => {
    paymentList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    employeeId: null,
    salaryMonth: null,
    paymentStatus: null,
    paymentDate: null,
    delFlag: null,
    createdAt: null
  }
  proxy.resetForm("paymentRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加工资发放记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getPayment(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改工资发放记录"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["paymentRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updatePayment(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addPayment(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除工资发放记录编号为"' + _ids + '"的数据项？').then(function() {
    return delPayment(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('payment/payment/export', {
    ...queryParams.value
  }, `payment_${new Date().getTime()}.xlsx`)
}

/** 查看工资条信息 */
async function handleSlip(row) {
  // 先清空工资条信息
  slipInfo.value = {}
  // 先关闭对话框
  slipOpen.value = false
  try {
    const response = await getSlip(row.employeeId)
    slipInfo.value = response.data
    // 数据加载完成后再打开对话框
    slipOpen.value = true
  } catch (error) {
    console.error('获取工资条信息失败:', error)
  }
}

/** 发放按钮操作 */
function handlePayment(row) {
  proxy.$modal.confirm('是否确认发放该工资？').then(function() {
    const paymentData = {
      id: row.id,
      employeeId: row.employeeId,
      salaryMonth: row.salaryMonth,
      paymentStatus: 'paid', // 已发放状态
      paymentDate: new Date()
    }
    return updatePayment(paymentData)
  }).then(() => {
    proxy.$modal.msgSuccess("发放成功")
    getList()
  }).catch(() => {})
}

getList()
</script>
